<template>
  <div>
    <Breadcrumb :items="['系统管理', '用户管理']" />
    <a-card class="general-card" title="用户管理">
      <template #extra>
        <a-space direction="horizontal" :size="18">
          <a-button v-authorities="[SYS_PM.SYS_USER_READ]" type="primary" :loading="loading" @click="refresh">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
          <a-button @click="userSearchModel.resetFields()">
            <template #icon>
              <icon-refresh />
            </template>
            重置
          </a-button>
        </a-space>
      </template>
      <a-form
        ref="userSearchModel"
        :model="searchModel"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left"
      >
        <a-row :gutter="16">
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item field="id" label="编号">
              <a-input
                v-model="searchModel.id"
                allow-clear
                placeholder="请输入用户编号"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item
              field="username"
              label="用户名"
            >
              <a-input
                v-model="searchModel.username"
                allow-clear
                placeholder="请输入用户名"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item
              field="nickname"
              label="昵称"
            >
              <a-input
                v-model="searchModel.nickname"
                allow-clear
                placeholder="昵称"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item
              field="phone"
              label="手机号"
            >
              <a-input
                v-model="searchModel.phone"
                allow-clear
                placeholder="请输入用户手机号"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="20" :md="12" :lg="8">
            <a-form-item
              field="gender"
              label="性别"
            >
              <a-select
                v-model="searchModel.gender"
                allow-clear
                placeholder="请选择性别"
              >
                <a-option :value="1">男</a-option>
                <a-option :value="0">女</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!--分割线-->
      <a-divider direction="horizontal" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button v-authorities="[SYS_PM.SYS_USER_WRITE]" type="primary" @click="onCreate">
              <template #icon>
                <icon-plus />
              </template>
              添加
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-space>
            <a-button>
              <template #icon>
                <icon-download />
              </template>
              下载
            </a-button>
            <table-column-setting v-model:columns="columns"/>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        :columns="columns"
        :data="tbData"
        :loading="loading"
        row-key="id"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"/>
    </a-card>
    <UserDrawer ref="userDrawer" @refresh="refresh" />
  </div>
</template>

<script setup lang="tsx">
import { onMounted, ref } from "vue";
import UserDrawer from "@/views/system/user/components/user-drawer.vue";
import TableColumnSetting from "@/components/table/table-column-setting.vue";
import { deleteById, listWithPagination } from "@/api/modules/system/user";
import usePaging from "@/hooks/paging";
import useLoading from "@/hooks/loading";
import type { UserParam, UserVo } from "@/types/modules/system";
import type { PaginationProps, TableColumnData } from "@arco-design/web-vue";
import dayjs from "dayjs";
import { SYS_PM } from "@/types/PM";

const userDrawer = ref<any>(null);
const searchModel = ref<UserParam>({});
const columns = ref<TableColumnData[]>([{
  title: "用户名",
  dataIndex: "username",
  width: 150,
  fixed: 'left'
}, {
  title: "昵称",
  dataIndex: "nickname",
  width: 150
}, {
  title: "头像",
  width: 80,
  dataIndex: 'avatar',
  render: ({ record }: { record: any }) => {
    return (
        <a-avatar>
          <img
              alt={record.nickname}
              src={record.avatar}
          />
        </a-avatar>
    )
  }
}, {
  title: "角色",
  dataIndex: "role",
  render: ({ record }: { record: any }) => {
    return (
        <a-space>
          {record.roles.map((role: { name: string }, index: number) => {
            if ([0, 1].includes(index)) {
              return (<a-tag>{role.name}</a-tag>);
            }
            if (index === 2) {
              return (<a-tag>...</a-tag>);
            }
            return {};
          })}
        </a-space>
    );
  }
},{
  title: "部门",
  dataIndex: "dept",
  render: ({ record }: { record: any }) => {
    return (
        <a-space>
          {record.depts.map((dept: { name: string }, index: number) => {
            if ([0, 1].includes(index)) {
              return (<a-tag>{dept.name}</a-tag>);
            }
            if (index === 2) {
              return (<a-tag>...</a-tag>);
            }
            return {};
          })}
        </a-space>
    );
  }
}, {
  title: "性别",
  width: 80,
  dataIndex: "gender",
  render: ({ record }: { record: any }) => {
    if (record.gender) {
      return <icon-man style="color: #0097CF" />;
    }
    return <icon-woman style="color: #E85B88" />;
  }
}, {
  title: "状态",
  width: 100,
  dataIndex: "enabled",
  render: ({ record }: { record: any }) => {
    return <a-switch
        type="round"
        unchecked-color="#F53F3F"
        v-model:model-value={record.enabled}
        checked-value={true}
        unchecked-value={false}
        disabled={true}
        v-slots={{
          checked: () => <span>正常</span>,
          unchecked: () => <span>异常</span>
        }}>
    </a-switch>
  }
}, {
  title: "锁定",
  dataIndex: "nonLocked",
  width: 100,
  render: ({ record }: { record: any }) => {
    return <div style="font-weight: bold">
      {record.nonLocked ? <icon-unlock style="color: cornflowerblue" /> : <icon-lock style="color: gray" />}
    </div>;
  }
}, {
  title: "注册日期",
  dataIndex: "createTime",
  width: 180,
  render: ({ record }: { record: any }) => {
    return dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')
  }
}, {
  title: "操作",
  width: 220,
  dataIndex: "operation",
  align: "right",
  fixed: "right",
  render: ({ record }: { record: any }) => {
    return <>
      <a-button v-authorities={Array.of(SYS_PM.SYS_USER_READ)}
                type="text"
                size="small"
                onClick={() => onPreview(record.id)}>
        预览
      </a-button>
      <a-button v-authorities={Array.of(SYS_PM.SYS_USER_WRITE)} type="text" size="small" onClick={() => onUpdate(record.id)} >
        编辑
      </a-button>
      <a-popconfirm content={`确定删除 '${record.nickname}' 吗?`} type="warning" onOk={() => onDelete(record.id)}>
        <a-button v-authorities={Array.of(SYS_PM.SYS_USER_WRITE)} type="text" size="small" status="danger">
          删除
        </a-button>
      </a-popconfirm>
    </>
  }
}]);
const userSearchModel = ref<any>()
const tbData = ref<UserVo[]>([]);
const { pageable, setPageable, prevPage } = usePaging();
const { loading, setLoading } = useLoading();

const pagination = ref<PaginationProps>({
  defaultCurrent: 1,
  defaultPageSize: 10
});

const onCreate = async () => {
  setLoading(true);
  await userDrawer.value.createHandle();
  setLoading(false);
};

const onUpdate = async (id: number) => {
  setLoading(true);
  await userDrawer.value.updateHandle(id);
  setLoading(false);
};

const onPreview = async (id: number) => {
  setLoading(true);
  await userDrawer.value.previewHandle(id);
  setLoading(false);
};

const onDelete = async (id: number) => {
  try {
    await deleteById(id);
    if (tbData.value.length <= 1) {
      prevPage();
    }
  } finally {
    await refresh();
  }
};

const refresh = async () => {
  setLoading(true);
  const { data } = await listWithPagination(pageable.value, searchModel.value);
  pagination.value = {
    current: data.current,
    pageSize: data.size,
    total: data.total,
    showTotal: true,
    showPageSize: true
  };
  tbData.value = data.records;
  setLoading(false);
};

const onPageChange = (page: number) => {
  setPageable(page - 1, pageable.value.size);
  refresh();
};

const onPageSizeChange = (pageSize: number) => {
  setPageable(pageable.value.page, pageSize);
  refresh();
};

onMounted(async () => {
  await refresh();
});

</script>

<script lang="tsx">
export default {
  name: "User"
};
</script>

<style scoped>

</style>
